package wowmobile;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

public class Threat {

    private Comparator<PlayerThreat> c = new ThreatComp();
    private PriorityQueue<PlayerThreat> threatQueue;
    private Map<Integer, Boolean> aliveMap;

    Threat(List<Integer> players) {
        threatQueue = new PriorityQueue<PlayerThreat>(1, c);
        aliveMap = new HashMap<Integer, Boolean>();
        List<Integer> playerscpy = new ArrayList<Integer>(players);
        PlayerThreat pthreat;
        int id;
        while (!playerscpy.isEmpty()) {
            id = playerscpy.remove(0);
            pthreat = new PlayerThreat(id, 0);
            aliveMap.put(id, Boolean.TRUE);
            threatQueue.add(pthreat);
        }
    }

    //podnosi całkowity threat gracza
    void raiseThreat(int playerId, float threat) {
        PlayerThreat pthreat;
        PriorityQueue<PlayerThreat> robQueue = new PriorityQueue<PlayerThreat>(1, c);
        while (!threatQueue.isEmpty()) {
            pthreat = threatQueue.remove();
            if(pthreat.getPlayerId() == playerId) {
                pthreat.setThreat(pthreat.getThreat()+threat);
            }
            robQueue.add(pthreat);
        }
        while (!robQueue.isEmpty()) {
            pthreat = robQueue.remove();
            threatQueue.add(pthreat);
        }
    }
    
    /*
     * pobiera gracza o najwyższym threat o ile żyje
     * w założeniu nie powinno być odpalone jak wszyscy nie żyją
     * zwraca -1 jak tak się stanie
     */
    int nextAttack() {
        PlayerThreat pthreat;
        PriorityQueue<PlayerThreat> robQueue = new PriorityQueue<PlayerThreat>(1, c);
        int nextAttack = -1;
        while (!threatQueue.isEmpty()) {
            pthreat = threatQueue.remove();
            if(aliveMap.get(pthreat.getPlayerId())) {
                nextAttack = pthreat.getPlayerId();
            }
            robQueue.add(pthreat);
        }
        while (!robQueue.isEmpty()) {
            pthreat = robQueue.remove();
            threatQueue.add(pthreat);
        }
        return nextAttack;
    }
    
    void died(int playerId) {
        aliveMap.remove(playerId);
        aliveMap.put(playerId, Boolean.FALSE);
    }
    
    void ressurected(int playerId) {
        aliveMap.remove(playerId);
        aliveMap.put(playerId, Boolean.TRUE);
    }
}
